package com.huluobo.a2302mdmdemo.pages

import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.lib_base.RoutePath
import com.hyphenate.EMCallBack
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMCursorResult
import com.hyphenate.chat.EMGroup
import com.hyphenate.chat.EMGroupInfo
import com.hyphenate.chat.EMMessage
import kotlinx.coroutines.launch

/**
 *  Created by LC on 2025/8/8.
 */

@Composable
fun GroupListPage(navHostController: NavHostController) {
    val groupList = remember {
        SnapshotStateList<EMGroupInfo>()
    }

    val joinedGroupList = remember {
        SnapshotStateList<EMGroup>()
    }

    var isJoined by remember {
        mutableStateOf(false)
    }


    LaunchedEffect(key1 = isJoined, block = {
        launch {
            if (isJoined) {
                //查找已加入的群
                EMClient.getInstance().groupManager()
                    .asyncGetJoinedGroupsFromServer(object : EMValueCallBack<List<EMGroup>> {
                        override fun onSuccess(value: List<EMGroup>?) {
                            if (value != null) {
                                joinedGroupList.clear()
                                joinedGroupList.addAll(value)
                            }
                        }

                        override fun onError(error: Int, errorMsg: String?) {
                            ToastUtils.showLong("查找已加入的群失败:$error,msg:$errorMsg")
                        }
                    })
            } else {
                //查找所有群
                EMClient.getInstance().groupManager()
                    .asyncGetPublicGroupsFromServer(10, "", object : EMValueCallBack<EMCursorResult<EMGroupInfo>> {
                        override fun onSuccess(value: EMCursorResult<EMGroupInfo>?) {
                            if (value != null) {
                                groupList.clear()
                                groupList.addAll(value.data)
                            }
                        }

                        override fun onError(error: Int, errorMsg: String?) {
                            Log.e("TagA", "获取讨论组失败:$error,msg:$errorMsg")
                        }
                    })
            }
        }
    })

    Column(
        Modifier
            .fillMaxWidth()
            .padding(20.dp)
    ) {
        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
            Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "", Modifier.clickable {
                navHostController.popBackStack()
            })
            Text(text = "讨论组", textAlign = TextAlign.Center)
            Icon(imageVector = Icons.Default.Add, contentDescription = "", Modifier.clickable {
                navHostController.navigate(RoutePath.CREATE_GROUP)
            })
        }
        Spacer(modifier = Modifier.height(10.dp))
        Button(modifier = Modifier.fillMaxWidth(), onClick = {
            isJoined = !isJoined
        }) {
            if (isJoined) {
                Text(text = "查找所有群")
            } else {
                Text(text = "查找已加入的群")
            }
        }
        Spacer(modifier = Modifier.height(10.dp))
        LazyColumn(
            content = {
                if (isJoined) {
                    items(joinedGroupList) {
                        JoinedGroupItem(emGroup = it, navHostController = navHostController)
                    }
                } else {
                    items(groupList) {
                        GroupItem(emGroupInfo = it)
                    }
                }
            },
            verticalArrangement = Arrangement.spacedBy(10.dp),
            modifier = Modifier.fillMaxWidth()
        )
    }
}

@Composable
fun JoinedGroupItem(emGroup: EMGroup, navHostController: NavHostController) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier
            .padding(10.dp)
            .fillMaxWidth()
    ) {
        Text(text = emGroup.groupName)
        Button(onClick = {
            //跳转聊天页面
            val chatBean = ChatBean(emGroup.groupId, EMMessage.ChatType.GroupChat, emGroup.groupName)
            val json = Gson().toJson(chatBean)
            navHostController.navigate(RoutePath.CHAT + "/$json")
        }) {
            Text(text = "进群聊天")
        }
    }
}

@Composable
fun GroupItem(emGroupInfo: EMGroupInfo) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween,
        modifier = Modifier
            .fillMaxWidth()
            .padding(10.dp)
    ) {
        Text(text = emGroupInfo.groupName)
        Button(onClick = {
            EMClient.getInstance().groupManager().asyncJoinGroup(emGroupInfo.groupId, object : EMCallBack {
                override fun onSuccess() {
                    ToastUtils.showLong("加入讨论组成功")
                }

                override fun onError(code: Int, error: String?) {
                    if (code == 601) {
                        ToastUtils.showLong("已经加入过该讨论组,无法再次加入")
                    } else {
                        ToastUtils.showLong("加入讨论组失败:$code,msg:$error")
                    }
                }
            })
        }) {
            Text(text = "加入讨论组")
        }
    }
}